package com.ohos.connent.accountcloud.biz.modular.dp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ohos.connent.accountcloud.biz.modular.dp.entity.DpEnterpriseInfo;
import com.ohos.connent.accountcloud.biz.modular.dp.entity.DpOrg;
import com.ohos.connent.accountcloud.biz.modular.dp.enums.CertifiedEnum;
import com.ohos.connent.accountcloud.biz.modular.dp.enums.DpExceptionEnum;
import com.ohos.connent.accountcloud.biz.modular.dp.enums.DpOrgCategoryEnum;
import com.ohos.connent.accountcloud.biz.modular.dp.enums.DpOrgStatusEnum;
import com.ohos.connent.accountcloud.biz.modular.dp.mapper.DpEnterpriseInfoMapper;
import com.ohos.connent.accountcloud.biz.modular.dp.param.*;
import com.ohos.connent.accountcloud.biz.modular.dp.service.AuthDpService;
import com.ohos.connent.accountcloud.biz.modular.dp.service.DpEnterpriseService;
import com.ohos.connent.accountcloud.biz.modular.dp.service.DpOrgService;
import com.ohos.connent.accountcloud.common.exception.CommonException;
import com.ohos.connent.accountcloud.common.page.CommonPageRequest;
import com.ohos.connent.accountcloud.common.util.CommonEmailUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 企业认证-service接口实现类
 *
 * @Author: ChenJiaHao
 * @Date: 2024/6/12 10:07
 * @Description:
 */
@Service
public class DpEnterpriseServiceImpl extends ServiceImpl<DpEnterpriseInfoMapper, DpEnterpriseInfo> implements DpEnterpriseService {

    @Resource
    private DpOrgService dpOrgService;
    @Resource
    private AuthDpService authDpService;

    @Override
    public Page<DpEnterpriseInfo> page(DpEnterprisePageParam dpEnterprisePageParam) {
        CertifiedEnum.validate(dpEnterprisePageParam.getType());
        QueryWrapper<DpEnterpriseInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(
                DpEnterpriseInfo::getId, DpEnterpriseInfo::getEnterpriseName, DpEnterpriseInfo::getEnterpriseNameEn,
                DpEnterpriseInfo::getAddress, DpEnterpriseInfo::getStatus, DpEnterpriseInfo::getCreateTime, DpEnterpriseInfo::getCertifiedTime);
        if (ObjectUtil.isNotEmpty(dpEnterprisePageParam.getSearchKey())) {
            queryWrapper.lambda().and(p -> p.like(DpEnterpriseInfo::getId, dpEnterprisePageParam.getSearchKey())
                    .or().like(DpEnterpriseInfo::getEnterpriseName, dpEnterprisePageParam.getSearchKey())
                    .or().like(DpEnterpriseInfo::getEnterpriseNameEn, dpEnterprisePageParam.getSearchKey()));
        }
        // 0为待审核页，1为已审核页面
        Integer type = dpEnterprisePageParam.getType();
        if (CertifiedEnum.PENDING_VERIFIED.getStatus() == type) {
            queryWrapper.lambda()
                    .in(DpEnterpriseInfo::getStatus, DpOrgStatusEnum.PENDING_REVIEW.getStatus(), DpOrgStatusEnum.REJECTED.getStatus())
                    .orderByDesc(DpEnterpriseInfo::getCreateTime);
        } else if (CertifiedEnum.REVIEWED.getStatus() == type) {
            queryWrapper.lambda()
                    .in(DpEnterpriseInfo::getStatus, DpOrgStatusEnum.VERIFIED.getStatus(), DpOrgStatusEnum.FROZEN.getStatus())
                    .orderByDesc(DpEnterpriseInfo::getCertifiedTime);
        } else {
            throw new CommonException("type参数错误");
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DpEnterpriseAddParam dpEnterpriseAddParam) {
        checkAddParam(dpEnterpriseAddParam);
        // 保存机构表
        QueryWrapper<DpOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DpOrg::getCategory, DpOrgCategoryEnum.COMPANY.getValue()).orderByDesc(DpOrg::getSortCode).last(" limit 1 ");
        DpOrg lastSortDpOrg = dpOrgService.getOne(queryWrapper);
        DpOrgAddParam dpOrgAddParam = new DpOrgAddParam()
                .setParentId("0")
                .setCategory(DpOrgCategoryEnum.COMPANY.getValue())
                .setName(dpEnterpriseAddParam.getEnterpriseName())
                .setSortCode(ObjectUtil.isEmpty(lastSortDpOrg) ? 1 : lastSortDpOrg.getSortCode() + 1);
        String dpOrgId = dpOrgService.add(dpOrgAddParam);

        // 保存企业认证详情表
        DpOrg dpOrg = dpOrgService.getById(dpOrgId);
        DpEnterpriseInfo dpEnterpriseInfo = BeanUtil.toBean(dpEnterpriseAddParam, DpEnterpriseInfo.class);
        dpEnterpriseInfo.setId(dpOrg.getCode()).setStatus(dpOrg.getStatus());
        this.save(dpEnterpriseInfo);

        // 更改用户的org_id
        authDpService.updateUserOrgId(dpOrg.getCode());
    }

    private void checkAddParam(DpEnterpriseAddParam dpEnterpriseAddParam) {
        DpEnterpriseInfo dpEnterpriseInfo = this.getOne(Wrappers.lambdaQuery(DpEnterpriseInfo.class)
                .eq(DpEnterpriseInfo::getBusinessLicenseNo, dpEnterpriseAddParam.getBusinessLicenseNo()));
        if (BeanUtil.isNotEmpty(dpEnterpriseInfo)) {
            throw new CommonException("存在重复的企业，企业名称：{}，证件号码：{}", dpEnterpriseInfo.getEnterpriseName(), dpEnterpriseInfo.getBusinessLicenseNo());
        }
        if (!PhoneUtil.isMobile(dpEnterpriseAddParam.getContactPhone())) {
            throw new CommonException("手机号码：{}格式错误", dpEnterpriseAddParam.getContactPhone());
        }
        if (!CommonEmailUtil.isEmail(dpEnterpriseAddParam.getContactEmail())) {
            throw new CommonException("邮箱：{}格式错误", dpEnterpriseAddParam.getContactEmail());
        }
    }

    @Override
    public DpEnterpriseInfo queryEntity(String id) {
        DpEnterpriseInfo dpEnterpriseInfo = this.getById(id);
        if (ObjectUtil.isEmpty(dpEnterpriseInfo)) {
            throw new CommonException("企业认证详情不存在，id值为：{}", id);
        }
        return dpEnterpriseInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(DpEnterpriseEditParam dpEnterpriseEditParam) {
        checkEditParam(dpEnterpriseEditParam);
        dpOrgService.update(Wrappers.lambdaUpdate(DpOrg.class)
                .eq(DpOrg::getCode, dpEnterpriseEditParam.getId())
                .set(DpOrg::getName, dpEnterpriseEditParam.getEnterpriseName())
                .set(DpOrg::getStatus, DpOrgStatusEnum.PENDING_REVIEW.getStatus()));

        DpEnterpriseInfo dpEnterpriseInfo = queryEntity(dpEnterpriseEditParam.getId()).setStatus(DpOrgStatusEnum.PENDING_REVIEW.getStatus());
        BeanUtil.copyProperties(dpEnterpriseEditParam, dpEnterpriseInfo);
        updateById(dpEnterpriseInfo);
    }

    private void checkEditParam(DpEnterpriseEditParam dpEnterpriseEditParam) {
        DpEnterpriseInfo dpEnterpriseInfo = this.getOne(Wrappers.lambdaQuery(DpEnterpriseInfo.class)
                .ne(DpEnterpriseInfo::getId, dpEnterpriseEditParam.getId())
                .eq(DpEnterpriseInfo::getBusinessLicenseNo, dpEnterpriseEditParam.getBusinessLicenseNo()));
        if (BeanUtil.isNotEmpty(dpEnterpriseInfo)) {
            throw new CommonException("存在重复的企业，企业名称：{}，证件号码：{}", dpEnterpriseInfo.getEnterpriseName(), dpEnterpriseInfo.getBusinessLicenseNo());
        }
        if (!PhoneUtil.isMobile(dpEnterpriseEditParam.getContactPhone())) {
            throw new CommonException("手机号码：{}格式错误", dpEnterpriseEditParam.getContactPhone());
        }
        if (!CommonEmailUtil.isEmail(dpEnterpriseEditParam.getContactEmail())) {
            throw new CommonException("邮箱：{}格式错误", dpEnterpriseEditParam.getContactEmail());
        }
    }

    @Override
    public String getThumbnail(MultipartFile file, DpEnterpriseThumbnailParam dpEnterpriseThumbnailParam) {
        String suffix = ObjectUtil.isNotEmpty(file.getOriginalFilename()) ? StrUtil.subAfter(file.getOriginalFilename(),
                StrUtil.DOT, true) : null;
        if (ObjectUtil.isNotEmpty(suffix)) {
            try {
                Integer height = dpEnterpriseThumbnailParam.getHeight();
                if (BeanUtil.isEmpty(height)) {
                    height = 750;
                }
                Integer width = dpEnterpriseThumbnailParam.getWidth();
                if (BeanUtil.isEmpty(width)) {
                    width = 300;
                }
                return ImgUtil.toBase64DataUri(ImgUtil.scale(ImgUtil.toImage(file.getBytes()), width, height, null), suffix);
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    @Override
    public String check() {
        DpEnterpriseInfo dpEnterpriseInfo = this.getById(authDpService.getLoginUser().getOrgId());
        checkLoginOrgIsForbidden(dpEnterpriseInfo);
        return dpEnterpriseInfo.getId();
    }

    /**
     * 根据企业认证的状态，前端跳转指定的页面
     * @param dpEnterpriseInfo 企业认证详情
     */
    private void checkLoginOrgIsForbidden(DpEnterpriseInfo dpEnterpriseInfo) {
        // 尚未认证
        if (BeanUtil.isEmpty(dpEnterpriseInfo)) {
            throw new CommonException(DpExceptionEnum.ENTERPRISE_UNVERIFIED.getCode(), DpExceptionEnum.ENTERPRISE_UNVERIFIED.getValue());
        }
        Integer status = dpEnterpriseInfo.getStatus();
        // 待审核
        if (DpOrgStatusEnum.PENDING_REVIEW.getStatus() == status) {
            throw new CommonException(DpExceptionEnum.ENTERPRISE_PENDING_REVIEW.getCode(), DpExceptionEnum.ENTERPRISE_PENDING_REVIEW.getValue());
        }
        // 认证驳回
        if (DpOrgStatusEnum.REJECTED.getStatus() == status) {
            throw new CommonException(DpExceptionEnum.ENTERPRISE_REJECTED.getCode(), DpExceptionEnum.ENTERPRISE_REJECTED.getValue());
        }
        // 企业冻结，用户账号不冻结
        if (DpOrgStatusEnum.FROZEN.getStatus() == status) {
            throw new CommonException(DpExceptionEnum.ENTERPRISE_FROZEN.getCode(), DpExceptionEnum.ENTERPRISE_FROZEN.getValue());
        }

        // 认证通过...
    }
}
